package cn.com.taiji.oospub.wechat.model;

import cn.com.taiji.oospub.wechat.common.Node;
import cn.com.taiji.oospub.wechat.common.util.JsonUtil;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class DataModel {
	private int page;// 当前页数

	private int pages;// 总页数

	private int total;// 总记录数

	private String value;
	
    private List rows;// 多条查询记录

    private HashMap resultMap;// 一条查询记录

	private String errCode;// 错误代码

	private String errMsg;// 错误信息


	public DataModel() {
		this.page = 0;
		this.pages = 0;
		this.total = 0;
		value = "";
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPages() {
		return pages;
	}

	public void setPages(int pages) {
		this.pages = pages;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getErrCode() {
		return errCode;
	}

	public void setErrCode(String errCode) {
		this.errCode = errCode;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}
	
    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }

    public HashMap getResultMap() {
        return resultMap;
    }

    public void setResultMap(HashMap resultMap) {
        this.resultMap = resultMap;
    }

	/**
	 * 转换dataModel的resultMap为json字符串
	 * 
	 * @return String
	 */
	@SuppressWarnings("unchecked")
    public String resultMapToJson() {
		JSONObject jo = null;
		try {
			if (resultMap != null && resultMap.size() > 0) {
				resultMap.put("errCode", errCode);
				resultMap.put("errMsg", errMsg);
				jo = (JSONObject) JSONSerializer.toJSON(resultMap);
				return jo.toString();
			} else {
				return "{\"errCode\":\"" + errCode + "\",\"errMsg\":\""
						+ errMsg + "\"}";
			}
		} catch (Exception e) {
			return "{\"errCode\":\"" + errCode + "\",\"errMsg\":\"" + errMsg
					+ "\"}";
		}
	}

	 /**
	 *
	 *
	 * @return String
	 */
	 public String resultListToJson() {
    	 JSONObject jo = null;
    	 try {
    	 HashMap<String, Object> map = new HashMap<String, Object>();
    	 if (rows != null && rows.size() > 0) {
        	 map.put("page", this.page);
        	 map.put("pages", this.pages);
        	 map.put("total", this.total);
        	 map.put("rows", this.rows);
        	 map.put("errCode", this.errCode);
        	 map.put("errMsg", this.errMsg);
        	 map.put("resultMap", this.resultMap);
    	 } else {
        	 map.put("page", "0");
        	 map.put("total", "0");
        	 map.put("records", "0");
        	 map.put("rows", this.rows);
        	 map.put("errCode", this.errCode);
        	 map.put("errMsg", this.errMsg);
        	 map.put("resultMap", this.resultMap);
    	 }
    	 jo = (JSONObject) JSONSerializer.toJSON(map);
    	 } catch (Exception e) {
    	 return "{}";
    	 }
    	 return jo.toString();
	 }

	/***************************************************************************
	 * @author:gaojm
	 * @dateTime:2011-02-09 13:30:30
	 * @param:
	 * @return:void
	 * @describe:把具有树形结构的结果集转换json字符串
	 **************************************************************************/
	public String resultTreeToJson() {
		List<Node> nodeList = new ArrayList();
		// 把rows里的hashmap变成Node
		if (rows == null || rows.size() < 1) {
			return "[]";
		} else {
			// 转换rows为树形节点结构
			nodeList = transformList(rows);
			JsonUtil jsonUtil = new JsonUtil();
			// 递归树形节点
			// jsonUtil.recursionFn(nodeList, (Node)nodeList.get(0));
			return jsonUtil.modifyNodeListStr(nodeList);
		}
	}
	
	private List<Node> transformList(List list) {
		List<Node> nodeList = new ArrayList<Node>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HashMap map = (HashMap) list.get(i);
				String id = map.get("id") == null ? "" : map.get("id") .toString();
				String text = map.get("text") == null ? "" : map.get("text") .toString();
				String parentId = map.get("parentId") == null ? "" : map.get("parentId").toString();
				String level = map.get("level") == null ? "" : map.get("level").toString();
				String checked = map.get("checked") == null ? null : map.get("checked").toString();// add by peiyong
				map.remove("id");
				map.remove("text");
				map.remove("parentId");
			    map.remove("checked"); // add by peiyong
				nodeList.add(new Node(id, parentId, text, level, checked, map));
			}
		} else {
			nodeList = null;
		}
		return nodeList;
	}

	public static String bean2json(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = object2json(props[i].getName());
					String value = object2json(props[i].getReadMethod().invoke(
							bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String list2json(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String array2json(Object[] array) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String map2json(Map<?, ?> map) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String set2json(Set<?> set) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String string2json(String s) {
		if (s == null) {
            return "";
        }
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}

	public static String object2json(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(string2json(obj.toString())).append("\"");
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			json.append(bean2json(obj));
		}
		return json.toString();
	}
	
	public static void main(String[] args) {
//		List<Role> list = new ArrayList<Role>();
//		Role po = new Role();
//		po.setName("");
//		po.setInfo("");
//		list.add(po);
//		System.out.print(list2json(list));
		System.out.print(string2json("sss"));
	}
}
